﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.Mod.Learning
{
    using SharingCenter.Web.Classes;
    using SharingCenter.Web.Classes.enums;
    using SharingCenter.Web.Classes.Learning;
    using SharingCenter.Web.Shared;
    using SharingCenter.Web.Classes.Messages;
    using System.Xml.Linq;
    using SharingCenter.Web.Classes.Scores;
    public partial class MyLearning : LearningPageBase
    {
        protected Sc_LearningHistory data;
        protected Sc_LearningProfile myProfile;
        protected Sc_LearningProfile otherProfile;

        protected void Page_Init(object sender, EventArgs e)
        {
            LinqDataSource1.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(LinqDataSource1_Selecting);
            ListView1.ItemDataBound += new EventHandler<ListViewItemEventArgs>(ListView1_ItemDataBound);
            ListView1.ItemCommand += new EventHandler<ListViewCommandEventArgs>(ListView1_ItemCommand);
        }

        void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            ListViewDataItem item = (ListViewDataItem)e.Item;
            Guid lhId = (Guid)ListView1.DataKeys[0].Value; //new Guid(ListView1.DataKeys[item.DataItemIndex].Value.ToString());
            Guid signOffUserId = new Guid(e.CommandArgument.ToString());
            switch (e.CommandName)
            {
                case "SignOff":
                    SignOffLearning(ref signOffUserId, ref lhId, ref e);
                    break;
            }
        }

        void SignOffLearning(ref Guid signOffUserId, ref Guid lhId, ref ListViewCommandEventArgs e)
        {
            bool isRequestorSigninOff = false;
            isRequestorSigninOff = LearningOperations.SignOffLearning(signOffUserId, lhId);
            // send message
            Sc_LearningHistory his = LearningOperations.GetHistoryByHistoryId(lhId, Profile.UserId);
            List<Guid> to = new List<Guid>();


            //Shared.Editor txtComment = (Shared.Editor)e.Item.FindControl("Editor1");
            TextBox txtComment = (TextBox)e.Item.FindControl("txtComment");
            string comment = txtComment.Text;
            HiddenField hdnSelectedScore = (HiddenField)e.Item.FindControl("SelectedScore");
            int score = int.Parse(hdnSelectedScore.Value.Substring(hdnSelectedScore.Value.Length - 1));

            XElement cxt = new XElement("Context",
                    new XAttribute("XsltFolderInMod", "Learning"),
                    new XElement("Event",
                        new XAttribute("Name", "LearningSignOff"),
                        new XElement("SignOffUserId", Profile.UserId.ToString()),
                        new XElement("LearningHistoryId", his.LearningHistoryId),
                        new XElement("Comment", comment),
                        new XElement("Score", score)));
            
            Sc_SharedScore scoreItem;
            
            if (isRequestorSigninOff)
            {
                MessageOperations.SendSystemMessage(his.RequestorUserId, his.RequesteeUserId, "LearningSignOff", cxt, true);
                scoreItem = ScoreOperations.AddScore(EntityType.LearningEvent, his.LearningHistoryId, score, his.RequestorUserId, his.RequesteeUserId, comment); 
            }
            else
            {
                MessageOperations.SendSystemMessage(his.RequesteeUserId, his.RequestorUserId, "LearningSignOff", cxt, true);
                scoreItem = ScoreOperations.AddScore(EntityType.LearningEvent, his.LearningHistoryId, score, his.RequesteeUserId, his.RequestorUserId, comment);
            }

            this.SetTopMostMessage("已经确认结束互助，消息已发送对方。", true);

            RefreshPage(true);
        }

        void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            LearningStatus status = LearningStatus.Active;
            this.data = (Sc_LearningHistory)((ListViewDataItem)e.Item).DataItem;
            bool imRequestor = data.RequestorUserId == Profile.UserId;
            
            ShowStatus(ref data, ref e, out status);
            ShowProfiles(ref data, ref e, ref imRequestor);
            HandleControlsInItem(ref data, ref e, ref imRequestor);
        }

        void HandleControlsInItem(ref Sc_LearningHistory data, ref ListViewItemEventArgs e, ref bool imRequestor)
        {
            Guid otherUserId = imRequestor ? data.RequesteeUserId : data.RequestorUserId;
            ((NickNameLink)e.Item.FindControl("NickNameLink1")).UserId = otherUserId;
            ((Panel)e.Item.FindControl("pnAction")).Visible = imRequestor ? !data.RequestorSignOff : !data.RequesteeSignOff;
            ((LinkButton)e.Item.FindControl("btnSignOff")).CommandArgument = (imRequestor ? data.RequestorUserId : data.RequesteeUserId).ToString();
            ((ThumbAvatar)e.Item.FindControl("otherAvatar")).UserId = otherUserId;
            ((PlaceHolder)e.Item.FindControl("phScore")).Visible = !data.RequestorSignOff || !data.RequesteeSignOff;
        }

        void ShowProfiles(ref Sc_LearningHistory data, ref ListViewItemEventArgs e, ref bool imRequestor)
        {
            //myProfile = (LearningProfileItem)("myProfile");
            //otherProfile = (LearningProfileItem)e.Item.FindControl("otherProfile");

            if (imRequestor)
            {
                myProfile = LearningOperations.Deserialize(data.RequestorProfile);
                otherProfile = LearningOperations.Deserialize(data.RequesteeProfile);
            }
            else
            {
                myProfile = LearningOperations.Deserialize(data.RequesteeProfile);
                otherProfile = LearningOperations.Deserialize(data.RequestorProfile);
            }

            ListView mySkillsInput = (ListView)e.Item.FindControl("lvMySkillsInput");
            mySkillsInput.DataSource = from t in myProfile.Sc_LearningIOs
                                       where t.Direction == LearningSkillDirection.Input
                                       select t;
            mySkillsInput.DataBind();
            ListView mySkillsOutput = (ListView)e.Item.FindControl("lvMySkillsOutput");
            mySkillsOutput.DataSource = from t in myProfile.Sc_LearningIOs
                                        where t.Direction == LearningSkillDirection.Output
                                        select t;
            mySkillsOutput.DataBind();

            ListView otherSkillsInput = (ListView)e.Item.FindControl("lvOtherSkillsInput");
            otherSkillsInput.DataSource = from t in otherProfile.Sc_LearningIOs
                                       where t.Direction == LearningSkillDirection.Input
                                       select t;
            otherSkillsInput.DataBind();
            ListView otherSkillsOutput = (ListView)e.Item.FindControl("lvOtherSkillsOutput");
            otherSkillsOutput.DataSource = from t in otherProfile.Sc_LearningIOs
                                        where t.Direction == LearningSkillDirection.Output
                                        select t;
            otherSkillsOutput.DataBind();
        }

        void ShowStatus(ref Sc_LearningHistory data, ref ListViewItemEventArgs e, out LearningStatus status)
        {
            string statusCssClass;
            string statusText;
            if (data.RequesteeSignOff && data.RequestorSignOff)
            {
                status = LearningStatus.Complete;
                statusCssClass = "ss-ballblue";
                statusText = "互助已结束";
            }
            else if (data.RequestorSignOff || data.RequesteeSignOff)
            {
                status = LearningStatus.SigningOff;
                statusCssClass = "ss-ballyellow";
                statusText = "等待确认结束";
            }
            else
            {
                status = LearningStatus.Active;
                statusCssClass = "ss-ballgreen";
                statusText = "互助正在进行";
            }
            Label st = (Label)e.Item.FindControl("lblStatus");
            st.CssClass = "iss " + statusCssClass;
            st.ToolTip += statusText;
            ((Literal)e.Item.FindControl("lblStatusText")).Text = statusText;
        }

        void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            if (Request.QueryString["id"] != null)
            {
                try
                {
                    e.Result = LearningOperations.GetHistoryByHistoryId(new Guid(Request.QueryString["id"]), Profile.UserId);
                }
                catch { RedirectToDefaultPage(); }
            }
            else
            {
                e.Result = LearningOperations.GetLearningHistoryByUserId(Profile.UserId);
            }
        }
    }
}
